<script setup lang="ts">
import { showLoadingToast, showToast, type ActionSheetAction } from 'vant';
import { onMounted, ref } from 'vue';
import { AreaColumns } from '../types/mk'
import base64ToBlob from 'b64-to-blob';
import { request } from '../api/index'

const showAvatarSheet = ref(false)
const actions = [
  { name: '相册' },
  { name: '拍照' },
];
const onCancel = () => showToast('取消');
const onSelect = async (action: ActionSheetAction, index: number) => {
  // 默认情况下点击选项时不会自动收起
  // 可以通过 close-on-click-action 属性开启自动收起
  showAvatarSheet.value = false;
  if (index === 0) {
    // 拉起相册
    const res = await mk.pickerPhoto()
    // 64转二进制
    onUpdateAvatar(res)
  } else if (index === 1) {
    // 拍照
    showToast(action.name)
  } else if (index === 2) {

  }
};
const onUpdateAvatar = async (data: string) => {
  try {
    showAvatarSheet.value = false
    showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    const image = base64ToBlob(data, 'image/jpeg')
    const fd = new FormData()
    fd.append('file', image, Date.now() + '.jpeg')
    const res = await request.post<MkResponse<{ avatar: string }>>('member/profile/avatar', fd)
    // userInfo.value.avatar = URL.createObjectURL(image)
    // 获取当前对象
    const user = mk.queryUser()
    // 本地图片修改
    user.avatar = res.data.result.avatar
    userInfo.value.avatar = user.avatar
    // 更新对象到接口
    mk.updateUser(user)
    showToast({ message: '上传成功' })
  } catch (err) {
    showToast({ message: '上传失败' })
  }
}
// 年月日选择
const showBirthdayBottom = ref(false)
const currentDate = ref(['2021', '01', '01']);
const minDate = new Date(1970, 1, 1)
const maxDate = new Date(2025, 5, 1)

// 获取地区
const showAreaBottom = ref(false)
// const currentAreaList = ref()
const areaList = ref<AreaColumns>({})
// 选择确认
const onSelectedLocation = ({ selectedValues, selectedOptions, selectedIndexes }) => {
  // 关闭窗口
  showAreaBottom.value = false
  // 展示选中内容
  // showToast(currentAreaList.value)
  // console.log(selectedValues);
  // console.log(selectedValues);
  // console.log(selectedOptions);
  // console.log(selectedIndexes);
  const arr = selectedOptions.map(item => { return item.text })
  console.log(arr);
  // 保存内容到fullLocation属性
  userInfo.value.fullLocation = arr.join(' ')
  console.log(userInfo.value.fullLocation);
  // 保存到对象
  userInfo.value.provinceCode = arr[0]
  userInfo.value.countyCode = arr[2]
  userInfo.value.cityCode = arr[1]
}
// 职业选择器
const showSelectorBottom = ref(false)
const selectJob = ref<string[]>([])
const columns = [
  { text: '老师', value: '老师' },
  { text: '程序员', value: '程序员' },
  { text: '医生', value: '医生' },
  { text: '公务员', value: '公务员' },
  { text: '事业单位', value: '事业单位' },
  { text: '销售经理', value: '销售经理' },
];
const onSelectorConfirm = ({ selectedValues }) => {
  showSelectorBottom.value = false
  // showToast(`当前值: ${selectedValues}`);
  // selectJob.value = [userInfo.value.profession]
  userInfo.value.profession = selectedValues
};
// mouted初始化加载
const userInfo = ref<ProfileInfo>({} as ProfileInfo)
onMounted(
  async () => {
    // 区域赋值
    const res = await mk.getAreaColumns()
    areaList.value = res
    // 获取个人信息
    const resInfo = await request.get<MkResponse<ProfileInfo>>('/member/profile')
    userInfo.value = resInfo.data.result
    console.log(userInfo.value)
    // 当前日期选择器更新为接口日期
    console.log('当前日期：' + userInfo.value.birthday);
    const dateInfo = userInfo.value.birthday.split('-')
    currentDate.value = dateInfo
    // 职业更新
    selectJob.value = [userInfo.value.profession]
  }
)

// 更新本地日期
const onConfirm = () => {
  showBirthdayBottom.value = false
  // console.log('选择日期：' + currentDate.value);
  // currentDate.value = [userInfo.value.birthday]
  // showToast('选择日期：' + currentDate.value)
  userInfo.value.birthday = currentDate.value.join('-')
}

// 提交修改
const onSubmit = async () => {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
  });
  console.log('这是保存前');
  console.log(userInfo.value);
  const res = await request.put<MkResponse<ProfileInfo>>('/member/profile', userInfo.value)
  // 强行赋值
  // res.data.result.fullLocation = userInfo.value.fullLocation
  // 全更新
  console.log(res.data.result);
  mk.updateUser(res.data.result)
  showToast('更新完毕')
}

</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image round width="100" height="100" class="avatar-img" :src="userInfo.avatar"
        @click="showAvatarSheet = true">
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>
    <!-- 修改头像选项 -->
    <van-action-sheet v-model:show="showAvatarSheet" :actions="actions" cancel-text="取消" close-on-click-action
      @cancel="onCancel" @select="onSelect" />
    <!-- 选择生日 -->
    <van-popup v-model:show="showBirthdayBottom" round position="bottom">
      <van-date-picker v-model="currentDate" title="选择日期" :min-date="minDate" :max-date="maxDate" @confirm="onConfirm"
        @cancel="showBirthdayBottom = false" />
    </van-popup>
    <!-- 选择地区 -->
    <van-popup v-model:show="showAreaBottom" round position="bottom">
      <van-area title="选择省市区" :area-list="areaList" @confirm="onSelectedLocation" @cancel="showAreaBottom = false" />
    </van-popup>
    <!-- 选择职业 -->
    <van-popup v-model:show="showSelectorBottom" round position="bottom">
      <van-picker v-model="selectJob" title="选择职业" :columns="columns" @confirm="onSelectorConfirm"
        @cancel="showSelectorBottom = false" />
    </van-popup>
    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" readonly v-model="userInfo.account"></van-field>
      <van-field label="昵称" placeholder="请输入昵称" v-model="userInfo.nickname"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group :icon-size="16" v-model="userInfo.gender">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field label="生日" readonly placeholder="请选择日期" @click="showBirthdayBottom = true"
        v-model="userInfo.birthday"></van-field>
      <van-field label="所在地" readonly placeholder="请选择所在地" @click="showAreaBottom = true"
        v-model="userInfo.fullLocation"></van-field>
      <van-field label="职业" readonly placeholder="请选择职业" @click="showSelectorBottom = true"
        v-model="userInfo.profession"></van-field>
    </van-cell-group>

    <div class="submit">
      <van-button round block type="primary" @click="onSubmit">
        保存资料
      </van-button>
    </div>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
